package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.constants.message.WmNewsUpDownConstants;
import com.heima.common.dtos.PageResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.common.util.JsonUtils;
import com.heima.model.media.dtos.*;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmAuditService;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-01
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 文章的上下架
     * @param dto
     * @return
     */
    @Override
    public void downOrUp(WmNewsDownOrUpDto dto) {
        if (dto == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null || userId == 0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews>  lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmNews::getWmUserId,userId);
        lqw.eq(WmNews::getId,dto.getId());
        WmNews wmNews = this.getOne(lqw);
        if (wmNews == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wmNews.getStatus() != 9){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNew = new WmNews();
        wmNew.setId(dto.getId());
        wmNew.setEnable(dto.getEnable());
        this.updateById(wmNew);

        Map<String,Object> map = new HashMap<>();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",dto.getEnable()?1L:0L);
//        成功后发送kafka消息
        kafkaTemplate.send(WmNewsUpDownConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JsonUtils.toString(map));


    }

    @Override
    public ResponseResult findOne(Integer id) {
        return ResponseResult.ok(this.getById(id));
    }

    @Override
    public ResponseResult listPage(WmNewsPageReqDto dto) {
        LambdaQueryWrapper<WmNews> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        lqw.eq(dto.getChannelId() != null,WmNews::getChannelId,dto.getChannelId());
        lqw.between(dto.getBeginPubDate() != null || dto.getEndPubDate() != null,
                WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        List<Integer> list = bulidStatus(dto.getStatus());
        lqw.in(!CollectionUtils.isEmpty(list),WmNews::getStatus,list);
        Integer userId = UserThreadLocalUtils.getUserId();
        lqw.eq(userId != null,WmNews::getWmUserId,userId);
        Page page = new Page(dto.getPage(),dto.getSize());
        Page page1 = this.page(page, lqw);
        if (CollectionUtils.isEmpty(page1.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return new PageResult(dto.getPage(), dto.getSize(), page1.getTotal(),page1.getRecords());
    }
    private List<Integer> bulidStatus(Integer status) {
        if (status == null || status == -1){
            return null;
        }
        if (status == 0){
            return Arrays.asList(0);
        }
        if (status == 1){
            return Arrays.asList(1,3);
        }
        if (status == 2){
            return Arrays.asList(2);
        }
        if(status == 4){
            return Arrays.asList(4, 8, 9);
        }
        return null;
    }
    @Autowired
    private WmMaterialService wmMaterialService;
    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private WmAuditService auditService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(WmNewsDto dto) {
        if (dto == null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer wmNewsId = dto.getId();

        //如果没有id  保存文章信息
        if (wmNewsId == null){
            //首先先保存文章
            WmNews wmNews = buildSaveWmnews(dto);
            this.save(wmNews);
            dto.setId(wmNews.getId());
            //关联内容中的图片素材信息
            List<WmNewsMaterial> newsMaterials =  buildWmNewsMaterial(dto);
            wmNewsMaterialService.saveBatch(newsMaterials);

        }else {
            //有id  修改文章信息
            WmNews wmNews = buildSaveWmnews(dto);
            updateById(wmNews);
            //先删除素材关联关系
            wmNewsMaterialService.deleteMatecial(wmNewsId);
            //关联内容中的图片素材信息
            List<WmNewsMaterial> newsMaterials =  buildWmNewsMaterial(dto);
            wmNewsMaterialService.saveBatch(newsMaterials);
        }
        if (dto.getDraft()){
            return;
        }
        // 自动审核, 异步审核
        log.info("开始自媒体文章审核");
        auditService.auditAsync(UserThreadLocalUtils.getUserId(),dto);

    }

    /**
     * 关联内容图片素材
     * @param dto
     */
    private List<WmNewsMaterial> buildWmNewsMaterial(WmNewsDto dto) {
        String content = dto.getContent();
        Integer dtoId = dto.getId();
        List<String> images = dto.getImages();


        List<WmNewsMaterial> newsMaterialList = new ArrayList<>();
        //正文
        List<WmNewsMaterial> contentImages = bulidWmMaterialFormContent(dtoId,content);
        if (contentImages != null){
            newsMaterialList.addAll(contentImages);
        }
        //封面
        List<WmNewsMaterial> coverImages = bulidWmMaterialFormCover(dtoId,images);
        if (coverImages != null){
            newsMaterialList.addAll(coverImages);
        }
        return newsMaterialList;
    }
    /**
     * 获取封面图片
     * @param wmNewId
     * @param images
     * @return
     */
    private List<WmNewsMaterial> bulidWmMaterialFormCover(Integer wmNewId, List<String> images) {
        if (CollectionUtils.isEmpty(images)){
            return null;
        }
        List<WmNewsMaterial> newsMaterialList = new ArrayList<>();
        for (String url : images) {
           WmNewsMaterial newsMaterial = bulidWmNewsMaterialCover(wmNewId,url);
           newsMaterialList.add(newsMaterial);
        }
        return newsMaterialList;
    }



    private WmNewsMaterial bulidWmNewsMaterialCover(Integer wmNewId, String url) {
        WmNewsMaterial newsMaterial = new WmNewsMaterial();
        newsMaterial.setOrd(1);
        newsMaterial.setType(MaterialType.ONEIMAGES.ordinal());
        WmMaterial wmMaterial = wmMaterialService.findAllByUrl(url);
        if (wmMaterial != null){
            newsMaterial.setMaterialId(wmMaterial.getId());
        }else {
            log.error("根据url查询素材为空，url：{}, wmNewsId:{}", url, wmNewId);
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        newsMaterial.setNewsId(wmNewId);
        return newsMaterial;

    }


    /**
     * 获取图片路径
     * @param content
     * @return
     */
    private List<WmNewsMaterial> bulidWmMaterialFormContent(Integer newId,String content) {
        //判断
        List<WmNewsContentDto> imageUrl = WmNewsContentDto.getImages(content);
        if (CollectionUtils.isEmpty(imageUrl)){
            return null;
        }
        return imageUrl.stream().map(item -> {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(item.getId());
            wmNewsMaterial.setNewsId(newId);
            wmNewsMaterial.setOrd(1);
            wmNewsMaterial.setType(MaterialType.CONTENT.ordinal());
            return wmNewsMaterial;
        }).collect(Collectors.toList());

    }

    /**
     * 添加文章信息
     * @param dto
     * @return
     */
    private WmNews buildSaveWmnews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        wmNews.setTitle(dto.getTitle());
        wmNews.setChannelId(dto.getChannelId());
        wmNews.setLabels(dto.getLabels());
        wmNews.setPublishTime(dto.getPublishTime());
        wmNews.setContent(dto.getContent());
        wmNews.setType(dto.getType());
        wmNews.setStatus(dto.getStatus());
        //            处理封面图片地址,多个地址使用，进行分割
        String images = dto.getImages().stream().collect(Collectors.joining(","));
        wmNews.setImages(images);
        if (dto.getId() == null ){
            wmNews.setCreatedTime(new Date());
            wmNews.setWmUserId(UserThreadLocalUtils.getUserId());
        }
        return wmNews;
    }


}
